package com.mdb.open.epay.resource;

import cn.hutool.core.date.DatePattern;
import com.mdb.bc.api.data.ResultEx;
import com.mdb.bc.api.enums.ApiEnum;
import com.mdb.bc.api.enums.ResultCode;
import com.mdb.bc.logger.LogAnnotation;
import com.mdb.bc.utils.ObjectUtil;
import com.mdb.bc.web.RepeatSubmitTypeEnum;
import com.mdb.bc.web.annotation.DenyRepeatSubmit;
import com.mdb.enums.content.ContentTypeEnum;
import com.mdb.open.epay.domain.bo.GetReconFileBo;
import com.mdb.open.epay.domain.dto.epay.GetReconFileDto;
import com.mdb.open.epay.domain.po.content.FileInfo;
import com.mdb.open.epay.domain.vo.epay.ReconFileVo;
import com.mdb.open.epay.facade.content.ContentFacade;
import com.mdb.open.epay.facade.epay.ReconFacade;
import com.mdb.user.LoginUserInfoHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 对账文件下载
 */
@RestController
@RequestMapping("")
@Api(tags = "对账管理")
public class ReconResource {


    @Autowired
    private ContentFacade contentFacade;
    @Autowired
    private ReconFacade reconFacade;

    @Autowired
    private LoginUserInfoHelper loginUserInfoHelper;

//    @LogAnnotation("獲取对账文件")
//    @ApiOperation("獲取对账文件")
//    @GetMapping("/qp/get_recon_file")
//    @ApiIgnore
//    public ResultEx<ReconFileVo> getReconFile(@ModelAttribute GetReconFileDto dto) {
//        String customerCode = loginUserInfoHelper.getCustomerCode(true);
//        GetReconFileBo getReconFileBo = new GetReconFileBo();
//        getReconFileBo.setCustomerCode(customerCode);
//        getReconFileBo.setReconDate(LocalDate.parse(dto.getReconDate(), DateTimeFormatter.ofPattern(DatePattern.PURE_DATE_PATTERN)));
//        getReconFileBo.setReconType(dto.getReconType());
//        return reconFacade.getReconFile(getReconFileBo);
//    }

    @DenyRepeatSubmit(type = RepeatSubmitTypeEnum.EXCLUSIVE_SUBMIT)
    @LogAnnotation
    @ApiOperation("对账文件下载")
    @GetMapping("/qp/download")
    public ResultEx download(@ModelAttribute GetReconFileDto dto, HttpServletRequest request, HttpServletResponse response) {
        //TODO 增加refer验证
        String customerCode = loginUserInfoHelper.getCustomerCode(true);

        GetReconFileBo getReconFileBo = new GetReconFileBo();
        getReconFileBo.setCustomerCode(customerCode);
        getReconFileBo.setReconDate(LocalDate.parse(dto.getReconDate(), DateTimeFormatter.ofPattern(DatePattern.PURE_DATE_PATTERN)));
        getReconFileBo.setReconType(dto.getReconType());
        ResultEx<ReconFileVo> reconFile = reconFacade.getReconFile(getReconFileBo);
        if (reconFile.isFailed()) {
            return reconFile;
        }

        String realFileNo = getRealFileNo(reconFile.getData().getFileNo());

        FileInfo fileInfo = contentFacade.getByFileNo(realFileNo);
        if (ObjectUtil.isEmpty(fileInfo)) {
            return ResultEx.makeDataNotExistsResult(ResultCode.DATA_NOT_EXISTS.getText());
        }

        response.setCharacterEncoding(request.getCharacterEncoding());
        ContentTypeEnum contentTypeEnum = ApiEnum.parse(ContentTypeEnum.class, fileInfo.getSuffix().toLowerCase());
        if (ObjectUtil.isEmpty(contentTypeEnum)) {
            contentTypeEnum = ContentTypeEnum.DEFAULT;
        }
        response.setContentType(contentTypeEnum.getText());
        FileInputStream fis = null;
        try {
            if (contentTypeEnum.getValue().equals(ContentTypeEnum.DEFAULT.getValue())) {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileInfo.getFileName(), "utf-8"));
            } else {
                response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileInfo.getFileName(), "utf-8"));
            }
            File file = new File(fileInfo.getFileUri());
            fis = new FileInputStream(file);

            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEx.fail();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultEx.ok();
    }

    /**
     * 获取文件真实编号
     */
    private String getRealFileNo(String fileNo) {
        if (fileNo.contains(".")) {
            return fileNo.substring(0, fileNo.lastIndexOf("."));
        }
        return fileNo;
    }

}